package com.ndood.gateway.app.web.mvc;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.CacheControl;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ndood.api.app.properties.ApiProperties;
import com.ndood.gateway.app.web.filter.CorsFilter;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
	
	@Autowired
	private ApiProperties apiProperties;
	
	/**
	 * 解决跨域问题
	 *https://blog.csdn.net/fouy_yun/article/details/82891616 
	 *http://www.uml.org.cn/j2ee/201711233.asp?weiid=1347
	 */
//	@Override
//    public void addCorsMappings(CorsRegistry registry) {
//        registry.addMapping("/**")
//                .allowedOrigins("*")
//                .allowedMethods("PUT", "DELETE", "GET", "POST", "OPTIONS")
//                .allowedHeaders("*")
//                .exposedHeaders("access-control-allow-headers",
//                        "access-control-allow-methods",
//                        "access-control-allow-origin",
//                        "access-control-max-age",
//                        "X-Frame-Options")
//                .allowCredentials(true).maxAge(3600);
//    }
	
	/**
	 * https://www.cnblogs.com/xiaoping1993/p/7873975.html
	 */
	@Bean
    public FilterRegistrationBean<CorsFilter> someFilterRegistration() {
		FilterRegistrationBean<CorsFilter> filterRegistrationBean = new FilterRegistrationBean<CorsFilter>();
		filterRegistrationBean.setFilter(new CorsFilter());
		filterRegistrationBean.setOrder(1);
		filterRegistrationBean.setEnabled(true);
		filterRegistrationBean.addUrlPatterns("/*");
		return filterRegistrationBean;
    }
	
	/**
	 * 静态资源映射
	 */
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		// 生产环境配置
		if (!apiProperties.getIsDevelop()) {
			String location = "classpath:/static/build/";
			// 解决springboot2.0找不到根目录下静态js文件问题
			registry.addResourceHandler("/static/**").addResourceLocations(location).setCacheControl(CacheControl.maxAge(7, TimeUnit.DAYS));
			registry.addResourceHandler("/favicon.ico").addResourceLocations(location + "favicon.ico");
		// 开发环境配置
		} else {
			String location = "classpath:/static/native/";
			registry.addResourceHandler("/static/**").addResourceLocations(location);
			registry.addResourceHandler("/favicon.ico").addResourceLocations(location + "favicon.ico");
		}
	}
	
	/**
	 * Jackson序列化
	 */
	@Bean
    public ObjectMapper getObjectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL); // 不序列化null的属性
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); // 默认的时间序列化格式
        return mapper;
    }
	
	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {

		MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
    	//设置日期格式
    	ObjectMapper objectMapper = getObjectMapper();
    	mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);
    	//设置中文编码格式
    	List<MediaType> list = new ArrayList<MediaType>();
    	list.add(MediaType.APPLICATION_JSON_UTF8);
    	mappingJackson2HttpMessageConverter.setSupportedMediaTypes(list);
    	converters.add(mappingJackson2HttpMessageConverter);
		
	}
	
	/**
	 * 解决springboot2.0不支持delete form的问题
	 * https://blog.csdn.net/moshowgame/article/details/80173817?utm_source=blogxgwz1
	 */
	@Bean
    public FilterRegistrationBean<HiddenHttpMethodFilter> testFilterRegistration3() {
        FilterRegistrationBean<HiddenHttpMethodFilter> registration = new FilterRegistrationBean<HiddenHttpMethodFilter>();
        registration.setFilter(new HiddenHttpMethodFilter());//添加过滤器
        registration.addUrlPatterns("/*");//设置过滤路径，/*所有路径
        registration.setName("HiddenHttpMethodFilter");//设置优先级
        registration.setOrder(2);//设置优先级
        return registration;
    }
	
}

